<template>
  <div class="mtree-box" ref="mtreeBox">
    <div class="secondrow">
      <div class="secondrowcontent">
        <!-- 搜索 -->
        <a-input-search
          v-if="config.search"
          v-model="keyWord"
          class="search-box"
          placeholder="请输入搜索关键字"
          @search="searchTree"
        />
        <!-- 专题 -->
        <el-dropdown
          trigger="click"
          @command="handleProject"
          class="project-box"
        >
          <el-dropdown-menu slot="dropdown">
            <el-dropdown-item
              v-for="item in projectArr"
              :key="item.name"
              :command="item.name"
            >
              <p>
                {{ item.name }}
                <a-icon type="check" v-show="item.name === projectName" />
              </p>
            </el-dropdown-item>
          </el-dropdown-menu>
          <el-button type="primary" size="small">
            <a-icon type="unordered-list" /> 专题
          </el-button>
        </el-dropdown>

        <el-button type="primary" size="small" @click="onFold('foldCheck')">
          <i class="selected"></i> 已选
        </el-button>
        <!-- 迷你树 -->
        <div class="tab-box" v-if="showLayerTreeMini">
          <div class="tabs-line" :class="{ active: tabName == 'mini' }"></div>
          <span
            :class="{ active: tabName == 'global' }"
            @click="setGlobalTreeData('global')"
            >全局图层</span
          >
          <span 
            :class="{ active: tabName == 'mini' }"
            @click="setPersonalTreeData('mini')"
            >个人图层</span
          >
        </div>
        <section class="function-box">
          <!-- 全部展开 -->
          <el-tooltip v-if="config.unfoldAll" placement="top">
            <template slot="content">
              <span>全部展开</span>
            </template>
            <div class="icon-box" @click="onFold('unfoldAll')">
              <a-icon type="turn_down" />
            </div>
          </el-tooltip>
          <!-- 全部折叠 -->
          <el-tooltip v-if="config.foldAll" placement="top">
            <template slot="content">
              <span>全部折叠</span>
            </template>
            <div class="icon-box" @click="onFold('foldAll')">
              <a-icon type="turn_up" />
            </div>
          </el-tooltip>
          <!-- 展开选中 -->
          <el-tooltip v-if="config.foldCheck" placement="top">
            <template slot="content">
              <span>展开选中</span>
            </template>
            <div class="icon-box" @click="onFold('foldCheck')">
              <a-icon type="selected" />
            </div>
          </el-tooltip>
          <!-- 与选中图层同步 -->
          <el-tooltip placement="top" v-if="config.sync">
            <template slot="content">
              <span>与选中图层同步</span>
            </template>
            <div class="icon-box" @click="selectLayer()">
              <a-icon type="arrow_rightleft" />
            </div>
          </el-tooltip>
        </section>
        <!-- 级别 -->
        <!-- <el-select size="small"  v-if="config.level" defaultValue="1" class="grade" @change="setGradebySelect">
                  <el-option value="1">L1</el-option>
                  <el-option value="2">L2</el-option>
                  <el-option value="3">L3</el-option>
                  <el-option value="4">L4</el-option>
                </el-select> -->
        <!-- 标签快捷搜索定位 -->
        <tag-nav
          v-if="config.tag"
          v-show="tabName == 'global'"
          @searchTree="searchTree"
        ></tag-nav>
      </div>
    </div>
    <!-- </div> -->
    <!-- 树 type="down" type="environment"-->
    <div
      class="tree-box ag-scrollbar"
      id="treeOva"
      v-loading="loading"
      element-loading-text="加载中"
      element-loading-spinner="el-icon-loading"
      element-loading-background="rgba(0, 0, 0, 0.8)"
    >
      <!-- 全局图层树 -->
      <a-tree
        v-if="treeData && treeData.length > 0 && tabName == 'global'"
        class="draggable-tree"
        draggable
        v-model="checkedKeys"
        @expand="onExpand"
        :expandedKeys="expandedKeys"
        @select="handleSelected"
        :treeData="treeData"
        :autoExpandParent="autoExpandParent"
        @rightClick="openTreeContextMenu"
        checkable
        @check="onCheck"
        ref="layerTreeRef"
      >
        <a-icon type="switcherIcon" />
        <template slot="title" slot-scope="item">
          <div @click="setLayerTreeIcon" class="backgroundcss">
            <div
              class="arrow_up"
              @click="setLayerTreeIcon"
              v-if="item.children"
            >
              <!-- <img src="./img/arrow_up.png"/> -->
            </div>
            <div
              class="total-child-layer"
              @click="setLayerTreeIcon"
              v-if="item.children"
            >
              {{ item.layerCount }}
            </div>

            <div
              class="left-box"
              v-if="!item.children && item.layerType != '130010'"
            >
              <i
                class="splitscreen"
                @click.stop="onCheckSplitScreen($event, item)"
              ></i>
              <!--<i class="location" v-bind:class="{ active: item.checked }" @click.stop="onCheckLocation(item)"></i>
              <i class="mult-menu" v-bind:class="{ active: item.checked }" @click.stop="openTreeContextMenu($event, item)"></i> -->
              <i class="location" @click.stop="onCheckLocation(item)"></i>
              <i
                class="mult-menu"
                @click.stop="openTreeContextMenu($event, item)"
              ></i>
            </div>
          </div>
          <div @click="setLayerTreeIcon" class="treeitemscss">
            <!-- <span class="index">{{ item.index }}class="folderpath"</span> -->
            <span
              :title="item.title"
              class="txt-ellipsis"
              :key="item.key"
              v-html="
                item.title.replace(
                  new RegExp(keyWord, 'g'),
                  '<span style=color:#f50>' + keyWord + '</span>'
                )
              "
            ></span>
          </div>
        </template>
      </a-tree>
      <!-- 个人图层树 -->
      <a-tree
        v-if="
          personalTreeData && personalTreeData.length > 0 && tabName == 'mini'
        "
        class="draggable-tree"
        draggable
        v-model="personalCheckedKeys"
        @expand="onExpand"
        :expandedKeys="expandedKeys"
        @select="handleSelected"
        :treeData="personalTreeData"
        :autoExpandParent="autoExpandParent"
        @rightClick="openTreeContextMenu"
        checkable
        @check="personalOnCheck"
        ref="personalLayerTreeRef"
      >
        <a-icon type="switcherIcon" />
        <template slot="title" slot-scope="item">
          <div
            @click="setLayerTreeIcon(item)"
            class="backgroundcss"
            :title="item.title"
          >
            <div
              class="arrow_up"
              @click="setLayerTreeIcon"
              v-if="item.children"
            >
              <!-- <img src="./img/arrow_up.png"/> -->
            </div>
            <div
              class="left-box"
              v-if="!item.children && item.layerType != '130010'"
            >
              <i
                class="splitscreen"
                @click.stop="onCheckSplitScreen($event, item)"
              ></i>
              <!--<i class="location" v-bind:class="{ active: item.checked }" @click.stop="onCheckLocation(item)"></i>
              <i class="mult-menu" v-bind:class="{ active: item.checked }" @click.stop="openTreeContextMenu($event, item)"></i> -->
              <i class="location" @click.stop="onCheckLocation(item)"></i>
              <i
                class="mult-menu"
                @click.stop="openTreeContextMenu($event, item)"
              ></i>
            </div>
          </div>
          <div @click="setLayerTreeIcon" class="treeitemscss">
            <!-- <span class="index">{{ item.index }}class="folderpath"</span> -->
            <span
              :title="item.title"
              class="txt-ellipsis"
              :key="item.key"
              v-html="
                item.title.replace(
                  new RegExp(keyWord, 'g'),
                  '<span style=color:#f50>' + keyWord + '</span>'
                )
              "
            ></span>
          </div>
        </template>
      </a-tree>
      <div v-if="treeData && treeData.length == 0" class="el-tree__empty-text">
        暂无数据
      </div>
    </div>
    <!-- 右键菜单 -->
    <div
      class="rt-menu-box"
      ref="rtMenuBox"
      v-show="isRtMenuShow"
      @mouseleave="hideTreeContextMenu"
    >
      <ul v-show="rtMenuObj.hasChild">
        <li @click="isExpandSelect(true)">
          <span>全部展开</span>
        </li>
        <li @click="isExpandSelect(false)">
          <span>全部折叠</span>
        </li>
      </ul>
      <ul v-show="!rtMenuObj.hasChild">
        <li
          v-for="item in rtMenuObj.list"
          :key="item.key"
          @click="handleMemuEvent(item.key)"
        >
          <span v-show="item.state">{{ item.name }}</span>
        </li>
      </ul>
    </div>
    <!-- 透明度 -->
    <a-popover
      :title="curSelectNode.title"
      trigger="click"
      v-model="opacityVisible"
    >
      <template slot="content">
        <el-slider
          :min="0"
          :max="1"
          :step="0.01"
          v-model="opacity"
          @input="changeOpacity"
        />
      </template>
      <span ref="opacityPoa" style="position: absolute"></span>
    </a-popover>

    <!--模型色彩-->
    <a-popover
      :title="curSelectNode.title"
      trigger="click"
      v-model="isModelColouration"
    >
      <template slot="content">
        <el-slider
          :min="0"
          :max="1"
          :step="0.01"
          v-model="modelColouration"
          @change="changeModelColouration"
        />
      </template>
      <span ref="modelColourationPoa" style="position: absolute"></span>
    </a-popover>

    <!-- 版本切换 -->
    <a-popover
      :title="curSelectNode.title"
      trigger="click"
      v-model="versionVisible"
    >
      <template slot="content">
        <el-radio-group
          name="radioGroup"
          :default-value="verArr[0]"
          @change="changeVersion"
        >
          <el-radio v-for="item in verArr" :key="item" :label="item">{{
            item
          }}</el-radio>
        </el-radio-group>
      </template>
      <span ref="versionPoa" style="position: absolute"></span>
    </a-popover>
    <layer-info
      @changeinfoVisible="closeLayerInfo"
      :infoVisible="infoVisible"
      :infoData="infoData"
    ></layer-info>

    <!-- 图层属性表 -->
    <layer-property-sheet ref="layerPropertySheetBox"></layer-property-sheet>
    <!-- 图例 -->
    <!-- <layer-legend ref="layerLegendBox"></layer-legend> -->
    <!-- 空间包显隐 -->
    <package-config
      ref="packageConfig"
      :curSelectNodeInfo="curSelectNodeInfo"
    ></package-config>
  </div>
</template>

<script>
import serverData from "@/views/js/api/imageDataApi";
import dirImageDataApi from "@/views/js/api/dirImageDataApi";
var axios = agcim.net.http;
import net from "@/views/js/net/serverData4Config";
import bus from "@/views/js/utils/bus";
import {
  getAllParentKey,
  getMenuKeys,
  getMenuKeysByLevel,
  getParentKey,
  restructTreeData,
  setTreeDetail,
} from "./js/index";
import TagNav from "./TagNav.vue";
import config from "./js/config";
import treeLayerOp from "./js/treeLayerOp";
import SplitScreen from "./js/splitScreen";
import layerInfo from "./LayerInfo";
import LayerPropertySheet from "./LayerPropertySheet.vue";
// import LayerLegend from "../Legend/index.vue";
import PackageConfig from "./packageConfigDialog.vue";

import contextMenu from "./js/contextMenu";
import { mapGetters } from "vuex";
import _ from "lodash";
let PickerHelper = agcim.interactive.PickerHelper;

let pickerHelper = null;
let viewer = null;
let tileset = null;
export default {
  name: "LayerTree",
  components: {
    "tag-nav": TagNav,
    "layer-info": layerInfo,
    "layer-property-sheet": LayerPropertySheet,
    // "layer-legend":LayerLegend,//图例移到工具箱里
    "package-config": PackageConfig,
  },
  data() {
    return {
      allPersonalLayersId: [],
      personalCheckedKeys: [],
      tabName: "global",
      //个人图层树数据
      personalTreeData: undefined,
      loading: true,
      config,
      //专题
      projectArr: [],
      //专题名
      projectName: "",
      //树
      treeData: undefined,
      //展开的key
      expandedKeys: [],
      //被选中的====
      checkedKeys: [],
      prevCheckedKeys: [],
      //树所有key
      treeAllKey: [],
      //是否自动展开父节点
      autoExpandParent: true,
      //右键菜单是否显示
      isRtMenuShow: false,
      //右键菜单
      rtMenuObj: contextMenu.rtMenuObj,
      //右键当前选中的
      curSelectNode: {},
      //搜索
      keyWord: "",
      //放图层列表
      layerArr: [],
      opacityVisible: false,
      opacity: 1,
      versionVisible: false,
      panelVisible: false,
      //版本切换
      verArr: [],
      //控制图层信息弹窗开关
      infoVisible: false,
      //图层信息
      infoData: null,
      //模型色彩设置
      isModelColouration: false,
      modelColouration: 0.2,
      //mini树
      compName: "",
      //个人小树列表
      miniTreeData: [],
      miniSelect: "请选择",
      isMini: false,
      curSelectNodeInfo: null,
      tdt_token: "8487c77b8410d6c9cd4a22cac7b0d902",
      dirId: null,
      checkedMark: false,
      // 记录分屏启动的dom节点
      splitScreenDom: {},
      // 记录分屏启动的node节点
      splitScreenNode: {},
    };
  },
  created() {
    this.getProjectInfo();
    //个人小树
    this.getMiniTreeData();
    this.getTokenInner().then((data) => {
      if (data.success && data.content.length > 0) {
        this.tdt_token = data.content[0].value;
      }
    });
  },
  mounted() {
    window.test = this;
    viewer = CIM.viewer;
    pickerHelper = new PickerHelper(viewer);
    var _this = this;
    this.$nextTick(() => {
      let o = document.getElementById("treeOva");
      o.style.maxHeight = document.body.clientHeight - 400 + "px";
      if (CIM.secondViewer) {
        $("#treeOva").addClass("linkage");
      }
    });
    bus.on("clearSplitScreenIcon", () => {
      this.clearSplitScreenIcon();
    });
    bus.on("initSplitScreenLayerTree", (viewer) => {
      this.initSplitScreenLayerTree(viewer);
    });
  },
  methods: {
    async handleProject(key) {
      //重置地图
      CIM.layerTree.removeAll();
      CIM.viewer.imageryLayers.removeAll();
      this.projectName = key;
      CIM_LAYERTREE_NAME = key;
      //重置dom tree
      this.getProjectInfo();
      this.getMiniTreeData();
      CIM.layerTree.layerTreeDom.setParentHandler(this);
      //重置CIM里面的tree
      let p = {
        projectName: this.projectName,
        emptydir: true,
      };
      let data = {};
      if (p.projectName !== this.$store.state.projectName) {
        data = await net.getLayerTreeData(p);
        this.$store.commit("changeProjectName", p.projectName);
        this.$store.commit("changeLayerTreeResult", data);
      } else {
        data = this.$store.state.layerTreeResult;
      }
      CIM.agcimScene.initialize(viewer, data);
      // this.$refs.layerLegendBox.init();
      this.$nextTick(() => {
        if (data.success && data.content[1].length > 0) {
          this.getLayTreeInit(data);
        }
      });
      //重置图例
      console.log(key);
      this.$store.commit("changeBaseLayerSwitch", key);
    },

    getLayTreeInit(data) {
      let currentTree = data.content[1].find(
        (item) => item.state.isShow === "1"
      );
      if (currentTree) {
        let o = this.setBaseLayer(currentTree);
        var layers = viewer.imageryLayers._layers;
        viewer.imageryLayers.remove(layers[0]);
        // viewer.imageryLayers.removeAll();
        viewer.imageryLayers.addImageryProvider(
          o.creationFunction(this.tdt_token),
          0
        );
        // this.markConfig.layer.name = ''; //当前开启注记的图层名
      }
    },
    getTokenInner() {
      return agcim.net.axiosWraper.getData(
        agcim.net.apiPath.keyvalue_findKeyValue +
          "?key=BaseLayerSwitcher_tdt_token"
      );
    },
    /**
     * @description: 根据底图类型来选中对应的服务
     * @param {*} params
     * @return {*}
     * @author: 谢小龙
     */
    setBaseLayer(params) {
      let layerObj = {};
      let layerInfo = JSON.parse(params.data);
      layerObj.name = params.text;
      layerObj.tooltip = params.nameCn;
      layerObj.iconUrl =
        agcim.net.apiPath.upload_layer_picture + layerInfo.picture;
      layerObj.mark =
        params.text.indexOf("天地图矢量") !== -1 ||
        params.text.indexOf("天地图影像") !== -1;
      if (params.layerType === "014000" || params.layerType === "021500") {
        layerObj.category = "地形";
      } else {
        layerObj.category =
          params.text.indexOf("注记") !== -1 ? "注记" : "底图";
      }
      layerObj.creationFunction = (viewer) => {
        if (params.layerType === "014000" || params.layerType === "021500") {
          CIM.layerTree.uncheckArcGISTiledElevationTerrain();
          if (!terrainLayerCollection) {
            terrainLayerCollection = new Cesium.cesiumTerrainLayerCollection(
              viewer
            );
          }
          terrainLayerCollection.addCesiumTerrainProvider({
            url: params.url,
            requestWaterMask: !0,
            requestVertexNormals: !0,
            isBase: true, //是否为底图地形，true为是
          });
        } else if (params.layerType === "070100") {
          return new Cesium.BingMapsImageryProvider({
            url: params.url,
            culture: "zh-Hans",
            mapStyle: Cesium.BingMapsStyle.AERIAL,
            key: "Avvezjpmf3GeI0DmNzagRT96r5tfujfHN2oZxem-uy5oXo7ksh0eR3r8hcpnrugE",
            minimumLevel: 1,
            maximumLevel: 20,
          });
        } else if (params.layerType === "090100") {
          return new Cesium.MapboxStyleImageryProvider({
            url: params.url,
            username: params.layerTable,
            styleId: "ckmvg2hdp0hlw17r1272s7lfx",
            accessToken:
              "pk.eyJ1IjoibWV0ZW9ybmlnaHQiLCJhIjoiY2ttdmZ5aWo3MDRxdzJwcXB0a20wOTJuYSJ9.sL9R5nchjHZdIJ-3nf5_cg",
          });
        } else if (
          params.layerType === "021101" ||
          params.layerType === "020202" ||
          params.layerType === "020302" ||
          params.layerType === "021102"
        ) {
          return new Cesium.ArcGisMapServerImageryProvider({
            url: params.url,
          });
        } else {
          return new Cesium.WebMapTileServiceImageryProvider({
            url: params.url,
            layer: params.layerTable,
            style: "default",
            format: "image/jpeg",
            tileMatrixSetID: "GoogleMapsCompatible",
            show: false,
            minimumLevel: 1,
            maximumLevel: 18,
          });
        }
      };
      return layerObj;
    },
    async getProjectInfo() {
      let res = await axios.get(agcim.net.apiPath.project_getProjectInfo, {
        params: { version: CIM_VERSION },
      });
      if (res.success) {
        this.projectArr = res.content;
        try {
          this.projectName = this.projectArr[0].name;
        } catch (e) {
          console.log(e);
        }
        this.buildLayerTree();
      }
    },
    /**创建图层树 */
    async buildLayerTree() {
      console.log('构建图层数');
      let vm = this;
      this.projectName = CIM_LAYERTREE_NAME;
      let p = {
        projectName: this.projectName,
        emptydir: true,
      };
      let res = {};
      if (p.projectName !== this.$store.state.projectName) {
        res = await net.getLayerTreeData(p);
        this.$store.commit("changeProjectName", p.projectName);
        this.$store.commit("changeLayerTreeResult", res);
      } else {
        res = this.$store.state.layerTreeResult;
      }
      var arr = res.content[0].children;
      vm.treeData = restructTreeData(arr, "", []).data;
      vm.getChild(vm.treeData);
      if (vm.treeData) this.loading = false;
      vm.checkedKeys = restructTreeData(arr, "", []).checkedData;
      this.prevCheckedKeys = vm.checkedKeys.slice(0);
      // vm.expandChecks();
      // let switchLayer = new agSwitchLayer();
      // switchLayer.addListener(CIM.viewer);
      return res;
    },
    //获取全部的子节点
    getChild(arr) {
      let vm = this;
      arr.map((item) => {
        item["layerCount"] = vm.getChildLayerCount(item);
        if (item.children && item.children.length) {
          vm.getChild(item.children);
        }
      });
      return arr;
    },
    // 计算layer数量
    getChildLayerCount(node) {
      let count = 0;
      // 定义一个函数
      function addChildLayerCount(node) {
        if (node.children && node.children.length) {
          for (let i = 0, len = node.children.length; i < len; i++) {
            addChildLayerCount(node.children[i]);
          }
        } else {
          count += !node.layerType ? 0 : 1;
          node["layerCount"] = count;
        }
        return count;
      }
      addChildLayerCount(node);
      return count;
    },
    //展开个人图层树勾选的
    expandPersonalChecks() {
      let vm = this;
      vm.expandedKeys = [];
      vm.checkedKeys.forEach((element) => {
        const arr_temp = getAllParentKey(element, vm.personalTreeData, []);
        vm.expandedKeys = [...vm.expandedKeys, ...arr_temp];
      });
      vm.expandedKeys = Array.from(new Set(vm.expandedKeys));
    },
    //展开默认勾选的
    expandChecks() {
      let vm = this;
      vm.expandedKeys = [];
      vm.checkedKeys.forEach((element) => {
        const arr_temp = getAllParentKey(element, vm.treeData, []);
        vm.expandedKeys = [...vm.expandedKeys, ...arr_temp];
      });
      vm.expandedKeys = Array.from(new Set(vm.expandedKeys));
    },
    onExpand(expandedKeys) {
      this.expandedKeys = expandedKeys;
      this.autoExpandParent = false;
    },
    //点击文字触发
    handleSelected(keys, info) {
      this.autoExpandParent = false;
      let itemKey = info.node.eventKey;
      if (this.expandedKeys.length > 0) {
        if (this.expandedKeys.includes(itemKey)) {
          this.expandedKeys.splice(this.expandedKeys.indexOf(itemKey), 1);
        } else {
          this.expandedKeys = [...this.expandedKeys, itemKey];
        }
      } else {
        this.expandedKeys = [itemKey];
      }
    },
    //展开折叠
    onFold(type) {
      debugger
      if(this.tabName=='global'){
        switch (type) {
        case "unfoldAll":
          let allkey = getMenuKeys(this.treeData, []);
          this.expandedKeys = allkey;
          this.setLayerTreeIcon();
          break;
        case "foldAll":
          this.expandedKeys = [];
          break;
        case "foldCheck":
          this.expandChecks();
          this.setLayerTreeIcon();
          break;
        default:
      }
      }else if(this.tabName=='mini'){
        switch (type) {
        case "foldCheck":
          this.expandPersonalChecks();
          // this.setLayerTreeIcon();
          break;
        default:
      }
      }
      
    },
    //隐藏右键的菜单
    hideTreeContextMenu: function (e) {
      this.isRtMenuShow = false;
    },
    //右键+点击 兼容
    openTreeContextMenu(e, val) {
      var multMenuItem = document.getElementsByClassName("mult-menu active");
      if (multMenuItem.length > 0) {
        multMenuItem[0].classList = "mult-menu";
      }
      contextMenu.setEnvi(this);
      if (val) {
        e.currentTarget.classList.value = "mult-menu active";
        contextMenu.showMenu(e, val);
      } else {
        // e.event.currentTarget.childNodes[0].childNodes[0].childNodes[1].childNodes[2].value = 'mult-menu active'
        // e.event.currentTarget.classList.value = 'mult-menu active'
        contextMenu.showMenu(e.event, e.node.dataRef);
      }
    },
    //全部打开，关闭（右键选中的）
    isExpandSelect(flag) {
      const arr1 = [this.curSelectNode];
      const b = getMenuKeys(arr1, []);
      if (flag) {
        for (let i in b) {
          if (this.expandedKeys.indexOf(b[i]) === -1) {
            this.expandedKeys.push(b[i]);
          }
        }
      } else {
        for (let i in b) {
          let index = this.expandedKeys.indexOf(b[i]);
          if (index > -1) {
            this.expandedKeys.splice(index, 1);
          }
        }
      }
      this.setLayerTreeIcon();
    },
    //控制级别显示
    setGradebySelect(n) {
      this.expandedKeys = [];
      this.expandedKeys = getMenuKeysByLevel(this.treeData, n, []);
    },
    //搜索
    searchTree(keyWord) {
      var vm = this;
      vm.keyWord = keyWord;
      vm.searchValue = vm.keyWord;
      if (vm.searchValue === "") {
        vm.expandedKeys = [];
      } else {
        vm.expandedKeys = [];
        let _backupsExpandedKeys = [];
        let currentTreeData = []
        if(this.tabName=='global'){
          currentTreeData = this.treeData
        }else if(this.tabName=='mini'){
          currentTreeData = this.personalTreeData
        }
        let candidateKeysList = vm.getkeyList(vm.searchValue, currentTreeData, []);
        candidateKeysList.map((item) => {
          var key = getParentKey(item, currentTreeData);
          if (key && !_backupsExpandedKeys.some((item) => item === key))
            _backupsExpandedKeys.push(key);
        });
        for (let i = 0; i < _backupsExpandedKeys.length; i++) {
          getAllParentKey(
            _backupsExpandedKeys[i],
            currentTreeData,
            _backupsExpandedKeys
          );
        }
        vm.expandedKeys = _backupsExpandedKeys.slice();
      }
      this.setLayerTreeIcon();
    },
    //获取节点title中含有value的所有key集合
    getkeyList(value, tree, keyList) {
      for (let i = 0; i < tree.length; i++) {
        let node = tree[i];
        if (node.text.indexOf(value) > -1) {
          keyList.push(node.key);
        }
        if (node.children) {
          this.getkeyList(value, node.children, keyList);
        }
      }
      return keyList;
    },
    //点击复选框
    onCheck(checkedKeys, e) {
      debugger
      treeLayerOp.onCheck(checkedKeys, e, this);
      this.personalCheckedKeys = checkedKeys;
      //同步首页缩略图数据
      this.$emit("changeMapThumbnail", checkedKeys);
    },
    personalOnCheck(checkedKeys, e) {
      if (!e.checked) {
        let removeId = [];
        for (let i = 0; i < this.allPersonalLayersId.length; i++) {
          if (checkedKeys.indexOf(this.allPersonalLayersId[i]) < 0) {
            removeId.push(this.allPersonalLayersId[i]);
          }
        }
        CIM.layerTree.removeMany(removeId);
      } else {
        CIM.layerTree.addMany(checkedKeys, CIM.viewer);
      }
    },
    //点击定位图标 node.layerType
    onCheckLocation(node) {
      treeLayerOp.zoomToLayer(node);
    },
    //点击分屏图标
    onCheckSplitScreen(e, node) {
      if (!CIM.secondViewer) {
        this.$message({
          message: "请先启用双屏联动功能",
          type: "warning",
        });
      } else {
        SplitScreen.splitScreen(node);
        if (node.splitScreen) {
          e.currentTarget.classList = "splitscreen active";
          if (!this.splitScreenDom[node.id]) {
            this.splitScreenDom[node.id] = e;
          }
          if (!this.splitScreenNode[node.id]) {
            this.splitScreenNode[node.id] = node;
          }
        } else {
          e.currentTarget.classList = "splitscreen";
          if (this.splitScreenDom[node.id]) {
            delete this.splitScreenDom[node.id];
          }
          if (this.splitScreenNode[node.id]) {
            delete this.splitScreenNode[node.id];
          }
        }
      }
    },
    // bus监听 用于双屏联动清理图层树分屏图标
    clearSplitScreenIcon() {
      let keys = Object.keys(this.splitScreenDom);
      if (keys.length > 0) {
        for (let key of keys) {
          this.splitScreenDom[key].target.classList = "splitscreen";
          SplitScreen._layerTree = null;
        }
      }
      let nodeKeys = Object.keys(this.splitScreenNode);
      if (nodeKeys.length > 0) {
        for (let nodeKey of nodeKeys) {
          var data = _.cloneDeep(this.treeData);
          this.getNodeWithId(nodeKey, data);
          this.treeData = data;
        }
      }
      this.splitScreenDom = {};
      this.splitScreenNode = {};
    },
    // 重置分屏flag
    getNodeWithId(id, data) {
      for (var item of data) {
        if (item.layers.length > 0) {
          for (var layer of item.layers) {
            if (layer.id === id) {
              layer.splitScreen = false;
            }
          }
        } else if(item.children.length > 0) {
          this.getNodeWithId(id, item.children);
        }
      }
    },
    // 初始化分屏layerTree
    initSplitScreenLayerTree(viewer) {
      SplitScreen._layerTree = null;
      SplitScreen._layerTree = new agcim.scene.LayerTree(viewer);
    },

    //菜单事件
    handleMemuEvent(key) {
      this.isRtMenuShow = false;
      this[key]();
    },
    //透明度调整
    changeOpacity(opacity) {
      CIM.layerTree.setLayerOpacityById(this.curSelectNode.id, opacity);
    },
    /**
     * 设置三维模型色彩.
     * 这个功能跟数据有一定的相关性。
     */
    changeModelColouration(opacity) {
      var model = CIM.layerTree.getLayerById(this.curSelectNode.id);
      if (model && model._primitives.length > 0) {
        model._primitives[0].imageBasedLighting._luminanceAtZenith = opacity;
      }
    },
    //缩放至图层
    zoomToLayerById() {
      CIM.layerTree.zoomToLayerById(this.curSelectNode.id);
    },
    //图层样式
    setLayerStyle() {
      let o = this.curSelectNode;
      this.$emit("LayerStyle", o);
    },
    //图层信息
    getLayerInfo() {
      let o = this.curSelectNode;
      this.infoVisible = true;
      this.infoData = o;
    },
    //图层属性表
    getLayerPropertySheet() {
      let o = this.curSelectNode;
      this.$refs.layerPropertySheetBox.onShow(o);
    },
    //空间包显隐藏
    selectSpace() {
      this.$nextTick(() => {
        this.$refs.packageConfig.onShow();
      });
      this.curSelectNodeInfo = {
        url: this.curSelectNode.url,
        id: this.curSelectNode.id,
      };
    },

    //因 visible 属性是由父组件来管理, 所以子组件触发此方法改变值;
    closeLayerInfo(val) {
      this.infoVisible = val;
    },
    //获取图层原始透明度--回显
    setOpacity() {
      this.opacityVisible = true;
      this.opacity = 1;

      let o = this.curSelectNode;
      let res = CIM.layerTree._aglayers.find((item) => {
        return item.id === o.id;
      });

      if (
        res._imageryLayers &&
        res._imageryLayers.length &&
        res._imageryLayers[0].alpha
      ) {
        this.opacity = res._imageryLayers[0].alpha;
        return;
      }

      //3dtiles
      if ("013000".indexOf(o.layerType) >= 0) {
        if (
          res._primitives.length &&
          res._primitives[0].style &&
          res._primitives[0].style._color &&
          res._primitives[0].style._color._expression
        ) {
          let str = res._primitives[0].style._color._expression;
          let index = str.lastIndexOf(",") + 1;
          this.opacity = parseFloat(str.substring(index, str.length - 1));
        }
        return;
      }

      //wfs
      if ("040003,030300,010300,021200,110310".indexOf(o.layerType) >= 0) {
        if (
          res._dataSource &&
          res._dataSource[0] &&
          res._dataSource[0].entities &&
          res._dataSource[0].entities.values &&
          res._dataSource[0].entities.values.length
        ) {
          let entity = res._dataSource[0].entities.values[0];
          let color = null;
          if (entity.polygon) {
            color = entity.polygon.material;
          } else if (entity.polyline) {
            color = entity.polyline.material;
          } else if (entity.point) {
            color = entity.point.color;
          }
          if (color) {
            this.opacity = color._value
              ? color._value.alpha
              : color.color._value.alpha;
          }
        }
      }
    },
    setModelColouration() {
      this.isModelColouration = true;
      this.modelColouration = 0.2;
    },
    setVersion() {
      this.versionVisible = true;
    },
    changeVersion(e) {
      let ly = CIM.layerTree._layerTreeData[this.curSelectNode.id];
      ly["defaultVersion"] = e;
      let new_url =
        ly["url1"] +
        ly.layerAggregateName +
        "/tileset.json?layerName=" +
        ly.text +
        "&version=" +
        e;
      ly.url = new_url;

      CIM.layerTree.removeLayerById(ly.id, CIM.viewer, 0);
      if (this.checkedKeys.indexOf(ly.id) > -1) {
        setTimeout(() => {
          CIM.layerTree.addMany([ly.id]);
        }, 500);
      }
    },
    selectLayer() {
      var vm = this;
      vm.$message.info("点击鼠标左键选择建筑，右键取消");
      pickerHelper.setCursor("crosshair");
      pickerHelper.on("LEFT_CLICK", function (movement) {
        let pickedFeature = viewer.scene.pick(movement.position);
        if (!pickedFeature || !pickedFeature.getProperty) {
          vm.$message.error("请选择一栋建筑");
          return;
        }
        let keyName = pickedFeature.primitive.agMetaData.nameCn;
        vm.searchTree(keyName);
        pickerHelper.reset();
      });
      //右键取消
      pickerHelper.on("RIGHT_CLICK", function (movement) {
        pickerHelper.reset();
      });
    },
    getIconUrl(type) {
      switch (type) {
        case "layers":
          return require("./img/layers.png");
        case "location_blue":
          return require("./img/position_blue.png");
        case "location":
          return require("./img/position.png");
        case "splitscreen":
          return require("./img/splitscreen.png");
        case "splitscreen_blue":
          return require("./img/splitscreen_blue.png");
        default:
          break;
      }
    },
    setLayerTreeIcon(item) {
      console.log(item);
      setTimeout(() => {
        let environmentclass = treeOva.getElementsByClassName("environment");
        //判断什么时候隐藏向下箭头
        if (environmentclass) {
          for (let i = 0; i < environmentclass.length; i++) {
            let treeitemscss = environmentclass[i].parentNode;
            let backgroundcss = treeitemscss.parentNode;
            let span = backgroundcss.childNodes[0];
            let span2 = backgroundcss.childNodes[1];
            let indexclass = span2.childNodes[0];
            let img = indexclass.childNodes[0];

            let imgsrc = this.getIconUrl("layers");
            img.setAttribute("src", imgsrc);
            let arrow_aspect = span.childNodes[0];
            arrow_aspect.style.display = "none";
          }
        }
      }, 100);
    },
    setGlobalTreeData(type) {
      let _this = this;
      this.tabName = type;
    },
    setPersonalTreeData(type) {
      let _this = this;
      this.tabName = type;
      let o = this.miniTreeData[0];
      if (!o) {
        return this.$message.info("请先建立个人图层");
      }
      // code = o.id;
      // let params = {
      //   id: o.id,
      //   dirId: _this.dirId,
      //   code: code,
      // };
      // //将当前字段替换为接口字段
      // let apiFieldList = {
      //   imageStoreId: params.id,
      //   imageStoreDirId: params.dirId,
      //   imageStoreCode: params.code
      // }
      // let res = await serverData.updateImageStore(apiFieldList);
      // if (res.success) {
      // this.getMiniTreeData();
      // }
    },
    //设置是否默认显示
    async setMiniTreeData(type) {
      let _this = this;
      if ("mini" == type && this.isMini) {
        return;
      }
      if ("global" == type && !this.isMini) {
        return;
      }
      let o = this.miniTreeData[0];
      if (!o) {
        return this.$message.info("请先建立个人图层");
      }
      let code = "";
      if ("mini" === type) {
        code = o.id;
      }
      let params = {
        id: o.id,
        dirId: _this.dirId,
        code: code,
      };
      //将当前字段替换为接口字段
      let apiFieldList = {
        imageStoreId: params.id,
        imageStoreDirId: params.dirId,
        imageStoreCode: params.code,
      };
      let res = await serverData.updateImageStore(apiFieldList);
      if (res.success) {
        this.getMiniTreeData();
      }
    },
    getPersonalTreeData() {
      let vm = this;
      console.log(vm.personalTreeData);
      vm.personalTreeData = [];
      vm.allPersonalLayersId = [];
      vm.personalCheckedKeys = [];
      let arr = this.miniTreeData;
      if (arr.length) {
        arr.forEach((item) => {
          if (item.imageStoreName == this.$store.state.projectName) {
            let a = JSON.parse(item.information);
            // if (arr[0].code) {
            // this.isMini = true;
            if (a.data && a.data.length) {
              let arr1 = setTreeDetail(a.data); //根据id取出真实图层arr
              console.log(
                "🚀 ~ file: index.vue ~ line 841 ~ getPersonalTreeData ~ arr1",
                arr1
              );
              // CIM.layerTree.removeAll();
              vm.personalTreeData = restructTreeData(arr1, "", []).data;
              console.log(vm.personalTreeData);
              if (vm.personalTreeData) this.loading = false;
              vm.getAllLayerId(vm.personalTreeData, vm.allPersonalLayersId);
              if (a.defaultCheck) {
                vm.personalCheckedKeys = a.defaultCheck.split(",");
                CIM.layerTree.addMany(vm.personalCheckedKeys, CIM.viewer);
                // }
                // } else {
                //   if (!this.isMini) {
                //     // this.getProjectInfo();
                //     // CIM.layerTree.layerTreeDom.setParentHandler(this);
                //   } else {
                //     // this.handleProject("自主CIM");
                //     this.isMini = false;
                //   }
              }
            }
          }
        });
      }
    },
    // 获取所有图层id数组
    getAllLayerId(tree, arr) {
      for (let i = 0; i < tree.length; i++) {
        if (tree[i].children && tree[i].children.length) {
          this.getAllLayerId(tree[i].children, arr);
        } else if (tree[i].url && tree[i].id) {
          arr.push(tree[i].id);
        }
      }
    },
    /**
     * @lastUpdateBy : 韩怡婷
     * @description: 新 获取个人树
     * @param {*}
     * @return {*}
     */
    async getMiniTreeData() {
      let vm = this;
      let code = { code: "other-AgCIM-LayerTreeMini" };
      let response = await dirImageDataApi.treeByCode(code);
      if (response.success && response.content.length > 0) {
        vm.dirId = response.content[0].imageStoreDirId;
      }
      let params = {
        dirCode: "other-AgCIM-LayerTreeMini", //自建个人目录树
        page: 1,
        rows: 1000,
      };
      let res = await serverData.selectAuthPageByDirCode(params);
      if (res.success) {
        let arr = this.apiFieldConvert(res.content.list);
        this.miniTreeData = arr;
        this.getPersonalTreeData();
      }
    },
    //将接口字段替换成当前使用的字段
    apiFieldConvert(list) {
      let listConvert = [];
      list.forEach((ele) => {
        let item = {
          ...ele,
          dirId: ele.imageStoreDirId,
          id: ele.imageStoreId,
          name: ele.imageStoreDirName,
          information: ele.imageStoreInformation,
          code: ele.imageStoreCode,
        };
        listConvert.push(item);
      });
      return listConvert;
    },
  },
  computed: {
    ...mapGetters(["viewLayerInfo"]),
    checkedKeysA() {
      this.checkedKeys;
      return CIM.layerTree._aglayerIds;
    },
    layerTreeMiniState() {
      return this.$store.state.layerTreeMiniState;
    },
    //是否启用个人图层树
    showLayerTreeMini(){
       return this.$store.state.showLayerTreeMini;
    }
  },
  watch: {
    viewLayerInfo: function (val) {
      this.checkedKeys = val;
      this.onFold("foldCheck");
    },
    checkedKeysA: function (val) {
      this.checkedKeys = val;
    },
    layerTreeMiniState: {
      immediate: true,
      deep: true,
      handler: function (newval) {
        if (newval) {
          this.getMiniTreeData();
          this.$store.state.layerTreeMiniState = false;
        }
      },
    },
    isRtMenuShow: function (val) {
      if (!val) {
        var multMenuItem = document.getElementsByClassName("mult-menu active");
        if (multMenuItem.length > 0) {
          multMenuItem[0].classList = "mult-menu";
        }
      }
    },

    // keyWord: function () {
    //   var vm = this;
    //   clearTimeout(vm.timer);
    //   vm.timer = setTimeout(function () {
    //     vm.searchTree();
    //   }, 500);
    // },
  },
};
</script>
<style scoped src="./css/index.css"></style>
<style>
/*一级以下的整体向前缩进  */
.mtree-box .tree-box ul li span.ant-tree-checkbox {
  /* right: 31px; */
  left: 5px;
}
/*一级以下的整体向前缩进  */
.mtree-box .tree-box ul li ul li span.ant-tree-checkbox {
  /* right: 31px; */
  left: 20px;
}
/* 二级以下的整体缩进 */
.mtree-box .tree-box ul li ul li ul li span.ant-tree-checkbox {
  /* right: 31px; */
  left: 40px;
}
/* 三级 */
.mtree-box .tree-box ul li ul li ul li ul li span.ant-tree-checkbox {
  /* right: 31px; */
  left: 60px;
}
/* 四级 */
.mtree-box .tree-box ul li ul li ul li ul li ul li span.ant-tree-checkbox {
  /* right: 31px; */
  left: 80px;
}
/* 五级 */
.mtree-box
  .tree-box
  ul
  li
  ul
  li
  ul
  li
  ul
  li
  ul
  li
  ul
  li
  span.ant-tree-checkbox {
  left: 100px;
}
/* 六级 */
.mtree-box
  .tree-box
  ul
  li
  ul
  li
  ul
  li
  ul
  li
  ul
  li
  ul
  li
  ul
  li
  span.ant-tree-checkbox {
  left: 120px;
}
</style>
